// lib/pages/notification/post_detail/post_detail_view.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';
import 'post_detail_logic.dart';

class PostDetailPage extends StatelessWidget {
  final logic = Get.find<PostDetailLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TitleBar.back(title: '帖子详情'),
      body: Obx(() {
        if (logic.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        final p = logic.post.value;
        if (p == null) {
          return Center(child: Text('帖子不存在', style: Styles.ts_8E9AB0_14sp));
        }
        return SingleChildScrollView(
          padding: EdgeInsets.all(16.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  AvatarView(width: 40.w, url: p.userAvatar),
                  SizedBox(width: 12.w),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(p.userName, style: Styles.ts_0C1C33_17sp_medium),
                      SizedBox(height: 4.h),
                      Text(
                        _formatTime(p.createdAt),
                        style: Styles.ts_8E9AB0_12sp,
                      ),
                    ],
                  ),
                ],
              ),
              SizedBox(height: 12.h),
              if (p.content.isNotEmpty)
                Text(p.content, style: Styles.ts_0C1C33_17sp),
              SizedBox(height: 12.h),
              if (p.tags.isNotEmpty) _buildTags(p),
              SizedBox(height: 8.h),
              if (p.images.isNotEmpty) _buildImageGrid(p.images),
            ],
          ),
        );
      }),
    );
  }

  String _formatTime(DateTime dt) {
    final now = DateTime.now();
    final diff = now.difference(dt);
    if (diff.inMinutes < 1) return '刚刚';
    if (diff.inHours < 1) return '${diff.inMinutes} 分钟前';
    if (diff.inDays < 1) return '${diff.inHours} 小时前';
    return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
  }

  Widget _buildTags(finalPost) {
    return Wrap(
      spacing: 8.w,
      runSpacing: 8.h,
      children: finalPost.tags.map<Widget>((t) {
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: (t.color != null && t.color!.isNotEmpty) ? Color(int.parse(t.color!.replaceFirst('#', ''), radix: 16) | 0xFF000000) : Styles.c_F0F2F6,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Text('#${t.name}', style: Styles.ts_0C1C33_12sp),
        );
      }).toList(),
    );
  }

  Widget _buildImageGrid(List<String> images) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: images.length == 1 ? 1 : (images.length == 2 ? 2 : 3),
        crossAxisSpacing: 4.w,
        mainAxisSpacing: 4.h,
        childAspectRatio: 1,
      ),
      itemCount: images.length > 9 ? 9 : images.length,
      itemBuilder: (context, index) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: Stack(
            fit: StackFit.expand,
            children: [
              Image.network(
                images[index],
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Styles.c_F0F2F6,
                    child: Icon(Icons.image_not_supported, color: Styles.c_8E9AB0),
                  );
                },
              ),
              if (index == 8 && images.length > 9)
                Container(
                  color: Colors.black54,
                  child: Center(
                    child: Text(
                      '+${images.length - 9}',
                      style: TextStyle(color: Colors.white, fontSize: 16.sp, fontWeight: FontWeight.bold),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }
}